package com.rykj.qxj.core;

import lombok.extern.log4j.Log4j;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Log4j
public class CorsFilter implements Filter {

	//http://10.151.228.11
	private String[] verifyReferer = new String[10];

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		verifyReferer = new String[]{"http://localhost","http://127.0.0.1","http://10.151.228.16","http://192.168.0.66","http://192.168.0.78","http://192.168.0.119","http://10.153.97.35","http://192.168.0.109","http://192.168.0.176",filterConfig.getInitParameter("hostUrl")};
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest) request;
		HttpServletResponse res = (HttpServletResponse) response;
		req.getRequestURI();
		res.setHeader("Access-Control-Allow-Origin", "*");
		res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, GET");
		res.setHeader("Access-Control-Max-Age", "3600");
		res.setHeader("Access-Control-Allow-Headers", "x-requested-with,appKey,Content-Type");
		chain.doFilter(req, res);
		/*String referer = ((HttpServletRequest)request).getHeader("Referer");
		boolean b = false;
		for(String vReferer : verifyReferer){
			if(referer==null || referer.trim().startsWith(vReferer)){
				b = true;
				log.info("跨域过滤器执行===========");
				HttpServletRequest req = (HttpServletRequest) request;
				HttpServletResponse res = (HttpServletResponse) response;
				log.info("访问地址："+req.getRequestURI());
				req.getRequestURI();
				res.setHeader("Access-Control-Allow-Origin", "*");
				res.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE, PUT, GET");
				res.setHeader("Access-Control-Max-Age", "3600");
				res.setHeader("Access-Control-Allow-Headers", "x-requested-with,appKey,Content-Type");
				chain.doFilter(req, res);
				break;
			}
		}
		if(!b){
			log.info("疑似CSRF攻击，referer:"+referer);
		}*/

	}

	@Override
	public void destroy() {

	}

}
